#include <iostream>
#include <string>
#include <etcd/Client.hpp>
#include <etcd/KeepAlive.hpp>
#include <etcd/Response.hpp>
#include <etcd/Value.hpp>
#include <etcd/Watcher.hpp>
#include <thread>

void callback(const etcd::Response& resp)
{
    if(resp.is_ok() == 0)
    {
        std::cout << "事件错误" << std::endl;
        return;
    }
    for(const auto& ev : resp.events())
    {
        if(ev.event_type() == etcd::Event::EventType::PUT)
        {
            std::cout << "服务信息发生改变" << std::endl;
            std::cout << "当前值 " << ev.kv().key() << " " << ev.kv().as_string() << std::endl;
            std::cout << "原先值 " << ev.prev_kv().key() << " " << ev.prev_kv().as_string() << std::endl;
        }
        else if(ev.event_type() == etcd::Event::EventType::DELETE_)
        {
            std::cout << "服务信息已经被删除" << std::endl;
            std::cout << "当前值 " << ev.kv().key() << " " << ev.kv().as_string() << std::endl;
            std::cout << "原先值 " << ev.prev_kv().key() << " " << ev.prev_kv().as_string() << std::endl;
        }
    }
}


int  main()
{
    std::string etcd_host = "http://127.0.0.1:2379";
    // 创建客户端
    etcd::Client client(etcd_host);
    // 获取指定的键值信息
    auto resp = client.ls("/service").get();
    if(resp.is_ok() == 0)
    {
        std::cout << "get error" << resp.error_message() << std::endl;
        return -1;
    }
    else
    {
        std::cout << "get suceese" << std::endl;
    }

    int sz = resp.keys().size();
    // std::cout << sz << std::endl;
    for(int i = 0; i < sz; ++i)
    {
        std::cout << resp.value(i).as_string() << " 提供功能 " << resp.value(i).key() << std::endl; 
    }
    // std::cout << "aaaaaaaaaaaaa" << std::endl;

    // 监控对象
    auto watcher = etcd::Watcher(client, "/service", callback, true);
    watcher.Wait();


    return 0;
}